/*** Class Name: ifulfillViewDependantFIController
 * Author: Accenture
 * Date: 13-July-2011
 * Requirement/Project Name: iFulfill
 * Requirement Description: link or unlink the current fulfillment item to another item within SFDC based on the same account, Product / Directory Code and Product Issue for a particular Advertiser. 
 *
 **/
 
public class ifulfillViewDependantFIController
{
    private Fullfilment_Item__c fulItem = new Fullfilment_Item__c();
    public List<Fullfilment_Item__c> fiList;
    public List<FullfilmentItemWrapper> wrapperItemList{get;set;}
    public List<FullfilmentItemWrapper> delinkItems{get;set;}
    public List<FullfilmentItemWrapper> releatedItems {get;set;}
   /**Constructor **/
    public ifulfillViewDependantFIController(ApexPages.StandardController controller) 
    {
         FulItem = (Fullfilment_Item__c)controller.getRecord();
         FullfilmentItemWrapper  i = new FullfilmentItemWrapper(null , false,0);
    }
    
      // FI Wrapper Class. 
     class FullfilmentItemWrapper
     {        
        public Fullfilment_Item__c prod{get;set;}        
        public boolean selectBox{get;set;}        
        public integer  color {get;set;} 
        Public FullfilmentItemWrapper(Fullfilment_Item__c fi, Boolean checkBox ,integer  color)
        {
            prod = fi;           
            selectBox = checkBox;   
            this.color = color;
        }  
    }
    
    /** Groups the related FI Objects with  another item based on the same Product / Directory Code and Product Issue for a particular Advertiser.**/    
    public pageReference doGroup()
    {
        List<Fullfilment_Item__c> updateRelatedItemlist = new List<Fullfilment_Item__c>();
        Decimal groupCounter = null;
        AppEndPoints__c appEndPoints= null;

        // Check if FI is already grouped with other FI 
         if(fulItem.group_id__c == null)
        {
            appEndPoints= [select Unique_GroupId__c from AppEndPoints__c];
            if(appEndPoints.Unique_GroupId__c == null)
            {
                appEndPoints.Unique_GroupId__c = 0;
             }
            appEndPoints.Unique_GroupId__c++;
            groupCounter = appEndPoints.Unique_GroupId__c;
            try
            {
                  // update the unique id.
                update appEndPoints;
            }
            catch(DMLException e )
            {
               IfullfillTextConstant.parseExceptionMsg(e,'ifulfillViewDependantFIController','doGroup');
            }    
             
        }
     
        for(Integer i=0 ; i< wrapperItemList.size(); i++)
        {   
             // Group all selected FI.   
            if(wrapperItemList[i].selectBox)
            {
                // the group id if FI is already grouped else new group id.
                if(fulItem.group_id__c == null)
                {             
                    wrapperItemList[i].prod.Group_Id__c = groupCounter;    
                }
                else
                {
                    wrapperItemList[i].prod.Group_Id__c =  fulItem.group_id__c;
                }
                updateRelatedItemlist.add(wrapperItemList[i].prod);       
             }    
              
         }       
        
        try
        {
               if(fulItem.group_id__c == null)
               {    
                    fulItem.group_id__c=groupCounter;
                    update fulItem;
               }
                // update the selected Fulfillment item
             Update updateRelatedItemlist;
                     
          }     
        Catch(DMLException e)
        {
            IfullfillTextConstant.parseExceptionMsg(e,'ifulfillViewDependantFIController','doGroup');
        }
        
         System.debug('updateReldlk>');
        Pagereference Page = new Pagereference('/'+FulItem.id);  
        return null;  
     }
          
     /** Returns FI object available for grouping**/        
     public list<FullfilmentItemWrapper> getsearchedRelatedItems()
     {
        wrapperItemList = new List<FullfilmentItemWrapper>();        
        fiList=[select Group_Id__c,id,name,Item_Id__c,UDAC__c,Customer_ID__c,Feature_Code__c,Region__c,Current_Stage__c,Owner_Reporting__c,Escalated__c,Current_Step__c, Status__c,Workflow_Name__c,account__r.name,Transaction_Type__c,Item_Version__c,Workflow_Version__c,Product_issue__c,Product_Code__c from Fullfilment_Item__c where
        account__c =:FulItem.account__c 
        and Product_Code__c =:fulitem.Product_Code__c 
        and id !=:fulitem.id 
        and Product_issue__c=:fulitem.Product_issue__c 
        and  (Group_Id__c = null or  Group_Id__c !=:FulItem.group_id__c)   ]; 

        if(fiList.size()>0)
        {
            for(Fullfilment_Item__c f :fiList)
            { 
               if(f.Group_Id__c  == null)
               {                 
                    wrapperItemList.add(new FullfilmentItemWrapper(f, false, -1));     
               }
               else
               {
                     wrapperItemList.add(new FullfilmentItemWrapper(f, false, 1));     
               }
            }
        }
        return wrapperItemList;
   }
 
 /**
 *
 *  Delink the will remove any previous link of the  FI. 
 *
 *
 */
   public void doDelink()
   {
        List<Fullfilment_Item__c> updateItemlist = new List<Fullfilment_Item__c>();
        for(FullfilmentItemWrapper Obj:delinkItems )
        {
            if(Obj.selectBox)
            {                
                Obj.prod.Group_Id__c = null;    
                updateItemlist.add(Obj.prod);          
            }   
        }
        try
        {
            Update updateItemlist;        
        }     
        catch(Exception e)
        {
            IfullfillTextConstant.parseExceptionMsg(e,'ifulfillViewDependantFIController','doDelink');
        }
        deLinkParentFI( FulItem );   
    }
    /**
        * Returns Grouped FI object.
        *
        */
    public List<FullfilmentItemWrapper> getGroupedItems()
    {
        delinkItems = new List<FullfilmentItemWrapper>();    
        List<Fullfilment_Item__c> fetcheditems = new list<Fullfilment_Item__c>();
        fetcheditems = [ select id,group_id__c,Customer_ID__c,Region__c,Escalated__c,Owner_Reporting__c,Current_Task_Indicator__c,Transaction_Type__c,Workflow_Version__c, name,Item_Id__c,UDAC__c,Feature_Code__c,Current_Stage__c,Current_Step__c, Status__c,Workflow_Name__c, account__r.name,Item_Version__c,Product_issue__c,Product_Code__c from Fullfilment_Item__c where 
        Group_Id__c =:FulItem.group_id__c and group_id__c!= null  and  name != :FulItem.name ];
        
         if(fetcheditems.size()>0)
         {
             for(Fullfilment_Item__c f :fetcheditems )
             {           
                 delinkItems.add(new FullfilmentItemWrapper(f, false,null));     
             }
         }
         return delinkItems ;    
     } 
     
     /*
      *   Delink the parent FI item if FI does not have any dependant FI.
      *
      **/
     
     private void deLinkParentFI(Fullfilment_Item__c fi )
     {
         Integer count = 0;
         if(fi.group_id__c != null  )
         {
             count  = [select count()  from Fullfilment_Item__c where group_id__c = :fi.group_id__c ] ;
             if(count == 1)
             {
                 fi.group_id__c = null;
                 try
                 {
                     update fi;
                 }
                 catch(Exception e)
                 {
                     IfullfillTextConstant.parseExceptionMsg(e,'ifulfillViewDependantFIController','deLinkParentFI');
                 }
             }
         }
     }    
 }